package com.sita.cfmoto.drivedata;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sita.cfmoto.R;
import com.sita.cfmoto.event.HasBindVehicleEvent;
import com.sita.cfmoto.rest.model.response.FetchVehicleDriveDayDataResponse;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.utils.DateUtils;
import com.sita.cfmoto.utils.FormatUtils;
import com.sita.cfmoto.utils.LocalStorage;
import com.sita.cfmoto.utils.NumberUtils;
import com.sita.cfmoto.utils.VehicleUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;
import me.everything.android.ui.overscroll.OverScrollDecoratorHelper;

public class DriveDataDay extends Fragment {

    private static final int LINE_COLOR = GlobalContext.getGlobalContext().getResources().getColor(R.color.common_text);
    private final String TAG = DriveDataDay.class.getSimpleName();
    @Bind(R.id.current_date)
    TextView dateView;
    @Bind(R.id.data_mileage)
    TextView mileageView;
    @Bind(R.id.data_time)
    TextView timeView;
    @Bind(R.id.data_power)
    TextView powerView;
    @Bind(R.id.data_average_speed)
    TextView avSpeedView;
    @Bind(R.id.data_ranking)
    TextView rankView;
    @Bind(R.id.scroll_container)
    ScrollView scrollViewContainer;
    @Bind(R.id.mileage_chart)
    LineChartView mileageChart;
    @Bind(R.id.speed_chart)
    LineChartView speedChart;
    @Bind(R.id.power_chart)
    LineChartView powerChart;
    //存放x轴的坐标
    ArrayList<String> xAxisDate = new ArrayList<>();
    private float mTotalMileage = 0;
    private long mTotalTime = 0; // unit is minute
    private float mTotalFuel = 0; // 油耗
    private int mAverageSpeed = 0; // km.h
    private int mRanking = 0; // 排名
    private List<PointValue> mMileagePointValues = new ArrayList<>();
    private List<AxisValue> mMileageAxisValues = new ArrayList<>();
    private List<PointValue> mSpeedPointValues = new ArrayList<>();
    private List<AxisValue> mSpeedAxisValues = new ArrayList<>();
    private List<PointValue> mPowerPointValues = new ArrayList<>();
    private List<AxisValue> mPowerAxisValues = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_drive_data_day, null);
        ButterKnife.bind(this, view);

        OverScrollDecoratorHelper.setUpOverScroll(scrollViewContainer);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        dateView.setText(DateUtils.formatDayOfWeek(calendar.getTimeInMillis()));

        resetTopTable();
        getDayValues();
        if (LocalStorage.hasBindVehicle()) {
            fetchData();
        }

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void onEventMainThread(HasBindVehicleEvent event) {
        if (event.hasBindVehicle) {
            fetchData();
        } else {
            resetTopTable();
            resetChart();
        }
    }

    private void fetchData() {
        VehicleUtils.fetchVehicleDriveDayState(new VehicleUtils.FetchVehicleDriveDayStateListener() {
            @Override
            public void onSuccess(FetchVehicleDriveDayDataResponse response) {
                if (response != null) {
                    mTotalMileage = response.mileageLastDay10;
                    mTotalTime = response.timesLastDay10;
                    mTotalFuel = response.oilLastDay10;
                    mAverageSpeed = FormatUtils.formatSpeed(response.speedLastDay10);
                    mRanking = response.rankLastDay10;
                    setTopTable();
                    initMileageChart(response);
                    initSpeedChart(response);
                    initPowerChart(response);
                }
            }
        });
    }

    private void resetTopTable() {
//        setTopTableData(0f, 0, 0f, 0f, 0);
        mileageView.setText("--");
        timeView.setText("--");
        avSpeedView.setText("--");
        powerView.setText("--");
        rankView.setText("--");
    }

    private void setTopTableData(float totalDistance, int seconds, float speed, float batteryCost, int ranking) {
        mileageView.setText(String.valueOf(NumberUtils.formatNumber(totalDistance)));
        timeView.setText(FormatUtils.formatTimeHour(seconds));
        avSpeedView.setText(String.valueOf(NumberUtils.formatNumber(speed)));
        powerView.setText(String.valueOf(NumberUtils.formatNumber(batteryCost)));
        rankView.setText(String.valueOf(ranking));
    }

    private void setTopTable() {
        setTopTableData(mTotalMileage / 1000f,
                (int) mTotalTime / 1000,
                mAverageSpeed,
                mTotalFuel,
                mRanking);
    }

    //x轴标注相同，只需要计算一次就可以
    private void getDayValues() {
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        int lastDay = calendar.get(Calendar.DATE);//得到前一天
        int currentMonth = calendar.get(Calendar.MONTH) + 1;//当前月份
        int currentYear = calendar.get(Calendar.YEAR);//当前年份
        if (lastDay >= 10) {
            for (int i = lastDay - 9; i <= lastDay; i++) {
                xAxisDate.add(String.valueOf(i) + "日");
            }
        } else {
            //先计算上一个月一共有多少天
            Calendar time = Calendar.getInstance();
            time.clear();
            time.set(Calendar.YEAR, currentYear);
            time.set(Calendar.MONTH, currentMonth - 2);//注意,Calendar对象默认一月为0
            int day = time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天数

            for (int i = 10 - lastDay; i > 0; i--) {
                xAxisDate.add(String.valueOf(day - i + 1) + "日");
            }
            for (int i = 1; i <= lastDay; i++) {
                xAxisDate.add(String.valueOf(i) + "日");
            }
        }
    }

    private void initMileageChart(FetchVehicleDriveDayDataResponse response) {
        ArrayList<Float> yData = new ArrayList<>();
        yData.add(response.mileageLastDay01 * 0.001f);
        yData.add(response.mileageLastDay02 * 0.001f);
        yData.add(response.mileageLastDay03 * 0.001f);
        yData.add(response.mileageLastDay04 * 0.001f);
        yData.add(response.mileageLastDay05 * 0.001f);
        yData.add(response.mileageLastDay06 * 0.001f);
        yData.add(response.mileageLastDay07 * 0.001f);
        yData.add(response.mileageLastDay08 * 0.001f);
        yData.add(response.mileageLastDay09 * 0.001f);
        yData.add(response.mileageLastDay10 * 0.001f);
        getAxisLables(xAxisDate, mMileageAxisValues);
        getAxisPoints(yData, mMileagePointValues);
        initLineChart(mMileagePointValues, mMileageAxisValues, mileageChart, Collections.max(yData));
    }

    private void resetChart() {
        mileageChart.setVisibility(View.INVISIBLE);
        speedChart.setVisibility(View.INVISIBLE);
        powerChart.setVisibility(View.INVISIBLE);
    }

    private void initSpeedChart(FetchVehicleDriveDayDataResponse response) {
        ArrayList<Float> yData = new ArrayList<>();
        yData.add(response.speedLastDay01);
        yData.add(response.speedLastDay02);
        yData.add(response.speedLastDay03);
        yData.add(response.speedLastDay04);
        yData.add(response.speedLastDay05);
        yData.add(response.speedLastDay06);
        yData.add(response.speedLastDay07);
        yData.add(response.speedLastDay08);
        yData.add(response.speedLastDay09);
        yData.add(response.speedLastDay10);
        getAxisLables(xAxisDate, mSpeedAxisValues);
        getAxisPoints(yData, mSpeedPointValues);
        initLineChart(mSpeedPointValues, mSpeedAxisValues, speedChart, Collections.max(yData));

    }

    private void initPowerChart(FetchVehicleDriveDayDataResponse response) {
        ArrayList<Float> yData = new ArrayList<>();
        yData.add(response.oilLastDay01);
        yData.add(response.oilLastDay02);
        yData.add(response.oilLastDay03);
        yData.add(response.oilLastDay04);
        yData.add(response.oilLastDay05);
        yData.add(response.oilLastDay06);
        yData.add(response.oilLastDay07);
        yData.add(response.oilLastDay08);
        yData.add(response.oilLastDay09);
        yData.add(response.oilLastDay10);
        getAxisLables(xAxisDate, mPowerAxisValues);
        getAxisPoints(yData, mPowerPointValues);
        initLineChart(mPowerPointValues, mPowerAxisValues, powerChart, Collections.max(yData));
    }

    /**
     * 初始化LineChart的一些设置
     */
    private void initLineChart(List<PointValue> mPointValues, List<AxisValue> mAxisValues, LineChartView mLineChartView, float mMaxValue) {
        mLineChartView.setVisibility(View.VISIBLE);
        Line line = new Line(mPointValues).setColor(LINE_COLOR).setCubic(false);  //折线的颜色
        List<Line> lines = new ArrayList<>();
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.SQUARE）
        line.setCubic(false);//曲线是否平滑
        line.setFilled(true);//是否填充曲线的面积
//      line.setHasLabels(true);//曲线的数据坐标是否加上备注
        line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(false);//是否显示圆点 如果为false 则没有原点只有点显示
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(true);
        axisX.setTextColor(Color.WHITE);  //设置字体颜色
        axisX.setTextSize(8);//设置字体大小
        axisX.setValues(mAxisValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
        axisX.setHasTiltedLabels(false);//x 轴字为水平
        Axis axisY = new Axis();  //Y轴
        axisY.setTextColor(Color.WHITE);  //设置字体颜色
        axisY.setTextSize(8);//设置字体大小
        data.setAxisYLeft(axisY);  //Y轴设置在左边

        //设置行为属性，支持缩放、滑动以及平移
        mLineChartView.setInteractive(true);
        mLineChartView.setZoomType(ZoomType.HORIZONTAL_AND_VERTICAL);
        mLineChartView.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        mLineChartView.setLineChartData(data);
        mLineChartView.setVisibility(View.VISIBLE);

        final Viewport v = new Viewport(mLineChartView.getMaximumViewport());
        v.bottom = 0;
        v.top = (float) (mMaxValue * 1.2);
        v.left = 0;
        v.right = 9;
        mLineChartView.setMaximumViewport(v);
        mLineChartView.setCurrentViewport(v);

        // 设置缩放倍数,so important(15可以看成是x坐标对应为15(x总共40),0看成是y 坐标对应为0)
        mLineChartView.setZoomLevelWithAnimation((float) 20, (float) 0, (float) 1);
    }

    /**
     * X 轴的值
     */
    private void getAxisLables(ArrayList<String> values, List<AxisValue> mAxisValues) {
        mAxisValues.clear();
        for (int i = 0; i < values.size(); i++) {
            mAxisValues.add(new AxisValue(i).setLabel(values.get(i)));
        }
    }

    /**
     * 图表的每个点的值
     */
    private void getAxisPoints(ArrayList<Float> values, List<PointValue> mPointValues) {
        mPointValues.clear();
        for (int i = 0; i < values.size(); i++) {
            mPointValues.add(new PointValue(i, values.get(i)));
        }
    }

}
